import os, sys, string, commands, random, time

class XXbsub:
	users = ['', 'fkong', 'qjia', 'jguo', 'pcui']
	projects = ['', 'Dev', 'QA', 'myproject']
	queues = ['', 'license', 'night', 'short', 'priority']
	cmds = ['', '/home/fkong/bin/pi.sh']
	MAX_JOB_NUM = 10000
	
	def __init__(self):
		pass
	
	def run(self):
		while(True):
			if (not self.exceed_max_job_num()):
				self.run_cmd()
				time.sleep(random.randint(0, 5))
			else :
				waiting_time = 600
				print 'Exceed max job num, waiting ' + str(waiting_time) + ' seconds.'
				time.sleep(waiting_time)
	
	def exceed_max_job_num(self):
		cmd = 'bjobs -u all | wc -l'
		result = commands.getstatusoutput(cmd)
		if(len(result) == 2):
			try:
				count = int(result[1])
				if (count > self.MAX_JOB_NUM):
					return True
			except:
				for i in range(1, len(result)):
					print result[i]
		return False
		
	def run_cmd(self):
		cmd = self.gen_cmd()
		result = commands.getstatusoutput(cmd)
		for i in range(1, len(result)):
			print result[i]
		print ''
	
	def gen_cmd(self):
		cmd = ''
		
		idx = random.randint(0, len(self.users) - 1)
		if (self.users[idx] != ''):
			cmd += 'sudo -u ' + self.users[idx] + ' '
		cmd += 'bsub '
		
		idx = random.randint(0, len(self.projects) - 1)
		if (self.projects[idx] != ''):
			cmd += '-P ' + self.projects[idx] + ' '
		
		idx = random.randint(0, len(self.queues) - 1)
		if (self.queues[idx] != ''):
			cmd += '-q ' + self.queues[idx] + ' '
		
		idx = random.randint(0, len(self.cmds) - 1)
		if (self.cmds[idx] != ''):
			cmd += self.cmds[idx] + ' '
		else:
			cmd += 'sleep ' + str(random.randint(1, 60)) + ' '
		
		print cmd
		return cmd
		
bsub = XXbsub()
bsub.run()

